package me.sdevil507.biz.common.area.service.impl;

import com.google.common.collect.Lists;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import me.sdevil507.biz.common.area.dto.CommonAreaParamsDto;
import me.sdevil507.biz.common.area.po.CommonAreaPo;
import me.sdevil507.biz.common.area.po.QCommonAreaPo;
import me.sdevil507.biz.common.area.repository.CommonAreaRepository;
import me.sdevil507.biz.common.area.service.CommonAreaService;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * 地区码表[CommonAreaServiceImpl]
 *
 * @author sdevil507
 * created on 2020-07-02 14:15:15
 */
@Service
public class CommonAreaServiceImpl implements CommonAreaService {

    @Resource
    private CommonAreaRepository commonAreaRepository;

    @Override
    public List<CommonAreaPo> readAll(CommonAreaParamsDto searchParamsDto) {
        QCommonAreaPo qCommonAreaPo = QCommonAreaPo.commonAreaPo;

        // 开启谓语查询条件
        Predicate predicate = qCommonAreaPo.areaId.isNotNull();

        Integer level = searchParamsDto.getLevel();
        if (null != level) {
            predicate = ExpressionUtils.and(predicate, qCommonAreaPo.level.eq(level));
        }

        Integer parentId = searchParamsDto.getParentId();
        if (null != parentId) {
            predicate = ExpressionUtils.and(predicate, qCommonAreaPo.parentId.eq(parentId));
        }

        // 排序
        Sort sort = Sort.by(new Sort.Order(Sort.Direction.ASC, "areaCode"));

        // 执行Iterable转换List
        return Lists.newArrayList(commonAreaRepository.findAll(predicate, sort).iterator());
    }

}